#!/bin/bash
set -exuo pipefail
#use set -exuo pipefail for more details

OSVERSION="$(sw_vers -productVersion)"

# normalizes the version numbers
v() {
  printf "%04d%04d%04d%04d%04d" $(for i in ${1//[^0-9]/ }; do printf "%d " $((10#$i)); done)
}

echo "OS version: ${OSVERSION}"

if [[ $(v $OSVERSION) > $(v "12.99") ]] ;then
	#printf 'Use this only for os version under 13.0.\n'
	exit 0
fi

# create the target directory if needed
if [[ ! -d "/Library/PrivilegedHelperTools" ]]; then
	/bin/mkdir -p "/Library/PrivilegedHelperTools"
	/bin/chmod 755 "/Library/PrivilegedHelperTools"
	/usr/sbin/chown -R root:wheel "/Library/PrivilegedHelperTools"
fi

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DAEMONAPP="$( echo $DIR | awk -F / '{print $7}' )"
DAEMON_APP_ID="$(basename ${DAEMONAPP} .app)"

# Define the paths to the source and target version files
DAEMON_SOURCE_VERSION="$DIR/version"
DAEMON_TARGET_VERSION="/Library/PrivilegedHelperTools/$DAEMON_APP_ID.app/Contents/Library/version"

	
# Function to read and compare file contents
compare_contents() {
    local source_content
    local target_content

    source_content=$(<"$1")
    target_content=$(<"$2")

    if [ "$source_content" = "$target_content" ]; then
        return 0  # Contents are the same
    else
        return 1  # Contents are different
    fi
}

# Function to check if an update is required
is_update_required() {
    local source_file="$1"
    local target_file="$2"

    # Check if the target file exists
    if [ ! -e "$target_file" ]; then
        return 0  # Target file does not exist, an update is required
    fi

    # Compare contents if the target file exists
    if compare_contents "$source_file" "$target_file"; then
        return 1  # Update is not required
    else
        return 0  # Update is required
    fi
}

# Check if an update is required
if is_update_required "$DAEMON_SOURCE_VERSION" "$DAEMON_TARGET_VERSION"; then
    DAEMON_SOURCE_PLIST_PATH="$DIR/launchd.plist"
    DAEMON_TARGET_PLIST_PATH="/Library/LaunchDaemons/$DAEMON_APP_ID.plist"

    DAEMON_SOURCE_APP_PATH="$DIR/../../../$DAEMON_APP_ID.app"
    DAEMON_TARGET_APP_PATH="/Library/PrivilegedHelperTools/$DAEMON_APP_ID.app"

    # Check if DAEMON_TARGET_PLIST_PATH already exists and unload it if needed
    if [ -e "$DAEMON_TARGET_PLIST_PATH" ]; then
        launchctl unload "$DAEMON_TARGET_PLIST_PATH"
    fi

    # Delete DAEMON_TARGET_APP_PATH if it exists
    if [ -e "$DAEMON_TARGET_APP_PATH" ]; then
        rm -rf "$DAEMON_TARGET_APP_PATH"
    fi

    cp "$DAEMON_SOURCE_PLIST_PATH" "$DAEMON_TARGET_PLIST_PATH"
    chown root:wheel "$DAEMON_TARGET_PLIST_PATH"
    cp -R "$DAEMON_SOURCE_APP_PATH" "$DAEMON_TARGET_APP_PATH"
    launchctl load "$DAEMON_TARGET_PLIST_PATH"

fi
